package com.mdd.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.BeanMapUtils;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.ICompetitionService;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.validate.competition.*;
import com.mdd.admin.vo.competition.*;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.competition.*;
import com.mdd.common.exception.BaseException;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.competition.*;
import com.mdd.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 赛事列实现类
 * @author LikeAdmin
 */
@Service
public class CompetitionServiceImpl implements ICompetitionService {

    @Resource
    CompetitionMapper competitionMapper;

    @Resource
    CompetitionDetailMapper competitionDetailMapper;

    @Resource
    CompetitionApplyMapper competitionApplyMapper;

    @Resource
    CompetitionMatchMapper competitionMatchMapper;

    @Resource
    CompetitionMatchTeamMapper competitionMatchTeamMapper;

    @Resource
    CompetitionSiteMapper competitionSiteMapper;

    @Resource
    CompetitionScoreMapper competitionScoreMapper;

    @Resource
    CompetitionMatchDetailMapper competitionMatchDetailMapper;
    @Resource
    CompetitionRuleMapper competitionRuleMapper;


    /**
     * 赛事列列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<CompetitionListedVo>
     */


    @Override
    public PageResult<CompetitionListedVo> list(PageValidate pageValidate, CompetitionSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<Competition> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(StringUtils.isNotEmpty(searchValidate.getKeyword()),a-> a.like("name", searchValidate.getKeyword()).or()
                .like("description",searchValidate.getKeyword()));
        queryWrapper.orderByDesc("id");

        competitionMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:keyword@name:str",
                "like:name:str",
                "=:cover:str",
                "=:address:str",
                "=:playTime@play_time:str",
                "like:playType@play_type:str",
                "=:schedule:str",
                "=:status:int",
                "=:orgParty@org_party:str",
                "=:orgId@org_id:long",
                "=:createId@create_id:int",
                "=:updateId@update_id:int",
        });

        IPage<Competition> iPage = competitionMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<CompetitionListedVo> list = new LinkedList<>();
        for(Competition item : iPage.getRecords()) {
            CompetitionListedVo vo = new CompetitionListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 赛事列详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return Competition
     */
    @Override
    public CompetitionDetailVo detail(Integer id) {
        Competition model = competitionMapper.selectOne(
                new QueryWrapper<Competition>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在");
        CompetitionDetail detail = competitionDetailMapper.selectOne(new LambdaQueryWrapper<CompetitionDetail>().eq(CompetitionDetail::getCompetitionId, id).last("limit 1"));
        CompetitionDetailVo vo = new CompetitionDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setCreateTime(TimeUtils.timestampToDate(model.getCreateTime()));
        vo.setUpdateTime(TimeUtils.timestampToDate(model.getUpdateTime()));
        if(ObjectUtils.isNotEmpty(detail)) {
            vo.setContent(detail.getContent());
            vo.setDetailId(detail.getId());
        }
        return vo;
    }

    /**
     * 赛事列新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(CompetitionCreateValidate createValidate) {
        Competition model = new Competition();
        model.setName(createValidate.getName());
        model.setCover(createValidate.getCover());
        model.setDescription(createValidate.getDescription());
        model.setPlayTime(createValidate.getPlayTime());
        model.setPlayEndTime(createValidate.getPlayEndTime());
        model.setRegistrationTime(createValidate.getRegistrationTime());
        model.setRegistrationEndTime(createValidate.getRegistrationEndTime());
        model.setPlayType(createValidate.getPlayType().stream().collect(Collectors.joining(",")));
        model.setSchedule(createValidate.getSchedule());
        model.setViewNum(createValidate.getViewNum());
        model.setStatus(createValidate.getStatus());
        model.setOrgParty(createValidate.getOrgParty());
        model.setOrgId(createValidate.getOrgId());
        model.setCreateId(createValidate.getCreateId());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateId(createValidate.getUpdateId());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        int insert = competitionMapper.insert(model);
        if(insert>0){
            CompetitionDetail detail = new CompetitionDetail();
            detail.setCompetitionId(model.getId());
            detail.setContent(createValidate.getContent());
            competitionDetailMapper.insert(detail);
        }
    }

    /**
     * 赛事列编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(CompetitionUpdateValidate updateValidate) {
        Competition model = competitionMapper.selectOne(
                new QueryWrapper<Competition>()
                        .eq("id",  updateValidate.getId())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setName(updateValidate.getName());
        model.setCover(updateValidate.getCover());
        model.setDescription(updateValidate.getDescription());
        model.setPlayTime(updateValidate.getPlayTime());
        model.setPlayEndTime(updateValidate.getPlayEndTime());
        model.setRegistrationTime(updateValidate.getRegistrationTime());
        model.setRegistrationEndTime(updateValidate.getRegistrationEndTime());
        model.setPlayType(updateValidate.getPlayType().stream().collect(Collectors.joining(",")));
        model.setSchedule(updateValidate.getSchedule());
        model.setStatus(updateValidate.getStatus());
        model.setViewNum(updateValidate.getViewNum());
        model.setOrgParty(updateValidate.getOrgParty());
        model.setOrgId(updateValidate.getOrgId());
        model.setCreateId(updateValidate.getCreateId());
        model.setUpdateId(updateValidate.getUpdateId());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        int i = competitionMapper.updateById(model);
        if(i>0){
            CompetitionDetail detail = new CompetitionDetail();
            detail.setCompetitionId(model.getId());
            detail.setContent(updateValidate.getContent());
            if(ObjectUtils.isNotEmpty(updateValidate.getDetailId())){
                detail.setId(updateValidate.getDetailId());
                competitionDetailMapper.updateById(detail);
            }else{
                competitionDetailMapper.insert(detail);
            }
        }
    }

    /**
     * 赛事列删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        Competition model = competitionMapper.selectOne(
                new QueryWrapper<Competition>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        competitionMapper.delete(new QueryWrapper<Competition>().eq("id", id));
    }

    @Override
    public void examine(CompetitionApplyExamineValidate updateValidate) {
        Competition competition = new Competition();
        competition.setId(updateValidate.getId());
        competition.setStatus(updateValidate.getStatus());
        competitionMapper.updateById(competition);
    }

    @Override
    public CompetitionSessionListedVo session(CompetitionSessionValidate sessionValidate) {
        Competition competition = competitionMapper.selectById(sessionValidate.getId());
        CompetitionSessionListedVo competitionSessionListedVo = new CompetitionSessionListedVo();
        if(competition.getPlayType().contains("1")||competition.getPlayType().contains("0")){
            List<CompetitionMatch> competitionMatches = competitionMapper.selectMatchList(sessionValidate.getId(),"1",sessionValidate.getSchedule());
            competitionSessionListedVo.setPlayTypeOne(competitionMatches);
        }
        if(competition.getPlayType().contains("2")||competition.getPlayType().contains("0")){
            List<CompetitionMatch> competitionMatches = competitionMapper.selectMatchList(sessionValidate.getId(),"2",sessionValidate.getSchedule());
            competitionSessionListedVo.setPlayTypeTwo(competitionMatches);
        }
        if(competition.getPlayType().contains("3")||competition.getPlayType().contains("0")){
            List<CompetitionMatch> competitionMatches = competitionMapper.selectMatchList(sessionValidate.getId(),"3",sessionValidate.getSchedule());
            competitionSessionListedVo.setPlayTypeThree(competitionMatches);
        }
        if(competition.getPlayType().contains("4")||competition.getPlayType().contains("0")){
            List<CompetitionMatch> competitionMatches = competitionMapper.selectMatchList(sessionValidate.getId(),"4",sessionValidate.getSchedule());
            competitionSessionListedVo.setPlayTypeFour(competitionMatches);
        }
        if(competition.getPlayType().contains("5")||competition.getPlayType().contains("0")){
            List<CompetitionMatch> competitionMatches = competitionMapper.selectMatchList(sessionValidate.getId(),"5",sessionValidate.getSchedule());
            competitionSessionListedVo.setPlayTypeFive(competitionMatches);
        }
        LambdaQueryWrapper<CompetitionSite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompetitionSite::getCompetitionId,competition.getId())
                .eq(CompetitionSite::getSchedule,competition.getSchedule());
        List<CompetitionSite> competitionSites = competitionSiteMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(competitionSites)){
            competitionSites.stream().forEach(f->{
                if(f.getPlayType()==1){
                    competitionSessionListedVo.setPlayAddressOne(f);
                }else if(f.getPlayType()==2){
                    competitionSessionListedVo.setPlayAddressTwo(f);
                }else if(f.getPlayType()==3){
                    competitionSessionListedVo.setPlayAddressThree(f);
                }else if(f.getPlayType()==4){
                    competitionSessionListedVo.setPlayAddressFour(f);
                }else if(f.getPlayType()==5){
                    competitionSessionListedVo.setPlayAddressFive(f);
                }
            });
        }
        return competitionSessionListedVo;
    }

    @Override
    public Integer bisai(CompetitionApplyExamineValidate updateValidate) throws Exception {
        Competition competition1 = competitionMapper.selectById(updateValidate.getId());
        CompetitionRule rule = competitionRuleMapper.selectOne(new LambdaUpdateWrapper<CompetitionRule>()
                .eq(CompetitionRule::getCompetitionId, updateValidate.getId())
                .eq(CompetitionRule::getSchedule, competition1.getSchedule())
        );
        if (ObjectUtils.isEmpty(rule)) {
            throw new BaseException(0,"赛事规则没有填写！",1);
        }
        if(StringUtils.isEmpty(rule.getGameTime())){
            rule.setGameTime("9:30~12:00;14:00~18:00");
        }
        if(rule.getPromotedNum()==null){
            rule.setPromotedNum(8);
        }
        if(rule.getIntervalTime()==null){
            rule.setIntervalTime(45);
        }
        List<String> timeIntervalList = generateTimeSlots(rule.getGameTime(), rule.getIntervalTime());
        return getScheduleOne(competition1,timeIntervalList,rule);
    }
    public int getScheduleOne(Competition competition1,List<String> timeIntervalList,CompetitionRule rule) throws Exception {

        if("1".equals(competition1.getSchedule())){
            //查询晋级的的人员
            List<CompetitionMatch> competitionMatchs = competitionMatchMapper.selectList(new LambdaQueryWrapper<CompetitionMatch>()
                    .eq(CompetitionMatch::getCompetitionId, competition1.getId())
                    // 1是轮空晋级，2是胜利晋级
                    .in(CompetitionMatch::getStatus, 1,2)
                    .eq(CompetitionMatch::getSchedule, competition1.getSchedule()));
            if(CollectionUtils.isNotEmpty(competitionMatchs)){
                long count = competitionMatchs.stream()
                        .filter(obj -> obj.getPlayOneScore() == null && obj.getPlayOneScore() == null)
                        .count();
                // 再次匹配
                List<String> collect = competitionMatchs.stream().map(m -> m.getResult()).collect(Collectors.toList());
                List<CompetitionApply> competitionApplies = competitionApplyMapper.selectList(new LambdaUpdateWrapper<CompetitionApply>().in(CompetitionApply::getTeamNo, collect));
                if (count != 0) {
                    if (rule.getGameFormat() == 1) {
                        paiMatch(competition1, competitionApplies, timeIntervalList, rule, rule.getPromotedNum());
                    } else if (rule.getGameFormat() == 2) {
                        paiJifenMatch(competition1, competitionApplies, timeIntervalList, rule, rule.getPromotedNum());
                    }
                    return 0;
                } else {
                    if (rule.getGameFormat() == 1) {
                        paiMatch(competition1, competitionApplies, timeIntervalList, rule, rule.getPromotedNum());
                    } else if (rule.getGameFormat() == 2) {
                        jiFenJinJi(competition1, rule);
                    }
                    return 1;
                }
            }else {
                //查询所有报名成功的人员
                List<CompetitionApply> competitionApplies = competitionApplyMapper.selectList(new LambdaQueryWrapper<CompetitionApply>()
                        .eq(CompetitionApply::getCompetitionId, competition1.getId())
                        .eq(CompetitionApply::getStatus, 1)
                        .groupBy(CompetitionApply::getApplyType,CompetitionApply::getTeamNo));
                if(rule.getGameFormat()==1) {
                    paiMatch(competition1, competitionApplies, timeIntervalList, rule, rule.getPromotedNum());
                }else if(rule.getGameFormat()==2){
                    paiJifenMatch(competition1,competitionApplies,timeIntervalList,rule,rule.getPromotedNum());
                }
            }
        }else if("2".equals(competition1.getSchedule())){
            List<CompetitionMatch> competitionMatchs = competitionMatchMapper.selectList(new LambdaQueryWrapper<CompetitionMatch>()
                    .eq(CompetitionMatch::getCompetitionId, competition1.getId())
                    .eq(CompetitionMatch::getStatus, 1)
                    .eq(CompetitionMatch::getSchedule, 2));
            if(CollectionUtils.isNotEmpty(competitionMatchs)){
                long count = competitionMatchs.stream()
                        .filter(obj -> obj.getPlayOneScore()==null&&obj.getPlayOneScore()==null)
                        .count();
                List<String> collect = competitionMatchs.stream().map(m -> m.getResult()).collect(Collectors.toList());
                List<CompetitionApply> competitionApplies = competitionApplyMapper.selectList(new LambdaUpdateWrapper<CompetitionApply>().in(CompetitionApply::getTeamNo, collect));
//                paiMatch(competition1,competitionApplies,timeIntervalList,rule,4);
                if(count!=0) {
                    if (rule.getGameFormat() == 1) {
                        paiMatch(competition1, competitionApplies, timeIntervalList, rule, 4);
                    } else if (rule.getGameFormat() == 2) {
                        paiJifenMatch(competition1, competitionApplies, timeIntervalList, rule, 4);
                    }
                    return 0;
                }else{
                    if (rule.getGameFormat() == 1) {
                        paiMatch(competition1, competitionApplies, timeIntervalList, rule, 4);
                    } else if (rule.getGameFormat() == 2) {
                        jiFenJinJi(competition1, rule);
                    }
                    return 1;
                }
            }
//        }else if("3".equals(competition1.getSchedule())){
//            List<CompetitionMatch> competitionMatchs = competitionMatchMapper.selectList(new LambdaQueryWrapper<CompetitionMatch>()
//                    .eq(CompetitionMatch::getCompetitionId, competition1.getId())
//                    .eq(CompetitionMatch::getStatus, 1)
//                    .eq(CompetitionMatch::getSchedule, 3));
//            if(CollectionUtils.isNotEmpty(competitionMatchs)) {
//                long count = competitionMatchs.stream()
//                        .filter(obj -> obj.getPlayOneScore()==null&&obj.getPlayOneScore()==null)
//                        .count();
//                List<String> collect = competitionMatchs.stream().map(m -> m.getResult()).collect(Collectors.toList());
//                List<CompetitionApply> competitionApplies = competitionApplyMapper.selectList(new LambdaUpdateWrapper<CompetitionApply>().in(CompetitionApply::getTeamNo, collect));
////                paiMatch(competition1, competitionApplies, timeIntervalList, rule, 1);
//                if(count!=0) {
//                    if(rule.getGameFormat()==1) {
//                        paiMatch(competition1, competitionApplies, timeIntervalList, rule, 1);
//                    }else if(rule.getGameFormat()==2){
//                        paiJifenMatch(competition1,competitionApplies,timeIntervalList,rule,1);
//                    }
//                    return 0;
//                }else{
//                    if (rule.getGameFormat() == 1) {
//                        paiMatch(competition1, competitionApplies, timeIntervalList, rule, 1);
//                    } else if (rule.getGameFormat() == 2) {
//                        jiFenJinJi(competition1, rule);
//                    }
//                    return 1;
//                }
//            }
        }
        return 0;
    }

    private void jiFenJinJi(Competition competition1,CompetitionRule rule){
        // 积分排序晋级
        MPJQueryWrapper<CompetitionApply> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.selectAll(CompetitionApply.class)
                .select("t2.name AS realName," +
                        "    t2.sheng_num," +
                        "    t2.bai_num," +
                        "    t2.jifen")
                .innerJoin(
                        "(select " +
                                "    t.id," +
                                "    t.name," +
                                "    t2.status," +
                                "    t2.match_id," +
                                "    SUM(CASE" +
                                "        WHEN t2.status = 1 THEN 1" +
                                "        ELSE 0" +
                                "    END) AS sheng_num," +
                                "    SUM(CASE" +
                                "        WHEN t2.status = 2 THEN 1" +
                                "        ELSE 0" +
                                "    END) AS bai_num," +
                                "    SUM(CASE" +
                                "        WHEN t2.status = 1 THEN 1" +
                                "        ELSE 0" +
                                "    END) * 3 AS jifen" +
                                "    from la_member t" +
                                "    inner join la_competition_apply t1 on t1.member_id = t.id" +
                                "    left join la_competition_match_team t2 on t1.team_no = t2.team_no" +
                                "    LEFT JOIN la_competition_match t3 ON t3.id = t2.match_id AND t3.schedule ="+competition1.getSchedule() +
                                "    where t1.competition_id ="+competition1.getId() +
                                "    group by id"+
                                ") t2 on t2.id = t.member_id"
                )
                .groupBy("t.team_no,t.member_id")
                .orderByDesc("t2.jifen")
                .orderByDesc("id");
        competitionApplyMapper.setSearch(queryWrapper, competition1, new String[]{
                "=:competitionId@t.competition_id:int",
        });
        List<CompetitionApplyListedVo> competitionApplyListedVos = competitionApplyMapper.selectJoinList(CompetitionApplyListedVo.class, queryWrapper);
        List<CompetitionMatchBiSaiVo> matches = new ArrayList<>();
        for (int i = 0; i < rule.getPromotedNum(); i++) {
            CompetitionApplyListedVo competitionApplyListedVo = competitionApplyListedVos.get(i);
            CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
            match.setCompetitionId(competition1.getId());
            int scheduleNum = Integer.valueOf(competition1.getSchedule()) + 1;
            match.setSchedule(scheduleNum+"");
            match.setPlayType(competitionApplyListedVo.getApplyType());
            match.setResult(competitionApplyListedVo.getTeamNo());
            match.setPlayOneScore(0);
            match.setPlayTwoScore(0);
            match.setStatus(1);
            matches.add(match);
        }
        if (CollectionUtils.isNotEmpty(matches)) {
            for (CompetitionMatchBiSaiVo bisai : matches) {
                CompetitionMatch match = new CompetitionMatch();
                BeanUtils.copyProperties(bisai, match);
                match.setId(null);
                int insert = competitionMatchMapper.insert(match);
                if (insert > 0) {
                    if (CollectionUtils.isNotEmpty(bisai.getList())) {
                        for (CompetitionMatchTeam matchTeam : bisai.getList()) {
                            CompetitionMatchTeam matchTeamNo = new CompetitionMatchTeam();
                            BeanUtils.copyProperties(matchTeam, matchTeamNo);
                            matchTeamNo.setMatchId(match.getId());
                            competitionMatchTeamMapper.insert(matchTeamNo);
                        }
                    }
                }
            }
        }
    }

    public void paiMatch(Competition competition1,List<CompetitionApply> competitionApplies,List<String> timeIntervalList,CompetitionRule rule,Integer personNum) throws Exception{
        if (CollectionUtils.isNotEmpty(competitionApplies)) {
            Map<Integer, List<CompetitionApply>> collect = competitionApplies.stream().collect(Collectors.groupingBy(CompetitionApply::getApplyType));
            if (ObjectUtils.isNotEmpty(collect)) {
                collect.forEach((k, v) -> {
                    List<CompetitionSite> competitionSites = competitionSiteMapper.selectList(new LambdaUpdateWrapper<CompetitionSite>()
                            .eq(CompetitionSite::getCompetitionId, competition1.getId())
                            .eq(CompetitionSite::getPlayType, k)
                            .eq(CompetitionSite::getSchedule, competition1.getSchedule()));
                    if(CollUtil.isEmpty(competitionSites)){
                        throw new BaseException(0,"赛事场地没有填写！",1);
                    }
                    List<CompetitionMatchBiSaiVo> matches = new ArrayList<>();
                    // 分组后，每组队员大于8个则进行匹配
                    Collections.shuffle(v);
                    if (v.size() == personNum) {
                        // 如果刚好等于晋级数量则全部晋级
                        v.forEach(f->{
                            CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
                            match.setCompetitionId(competition1.getId());
                            int scheduleNum = Integer.valueOf(competition1.getSchedule()) + 1;
                            match.setSchedule(scheduleNum+"");
                            match.setPlayType(f.getApplyType());
                            match.setResult(f.getTeamNo());
                            match.setPlayOneScore(0);
                            match.setPlayTwoScore(0);
                            match.setStatus(1);
                            matches.add(match);
                        });
                    } else if (v.size() > personNum) {
                        int size = v.size();
                        Integer num = generatePairings(size, personNum);
                        List<Integer> teamNo = drawByeTeams(size, num);
                        List<CompetitionApply> teamList = getTeamList(teamNo, v);
                        teamList.stream().forEach(f->{
                            CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
                            match.setCompetitionId(competition1.getId());
                            match.setSchedule(competition1.getSchedule());
                            match.setPlayType(f.getApplyType());
                            match.setResult(f.getTeamNo());
                            match.setPlayOneScore(0);
                            match.setPlayTwoScore(0);
                            // 轮空晋级
                            match.setStatus(1);
                            matches.add(match);
                        });
                        // 从所有队伍列表中移除轮空队伍
                        v.removeAll(teamList);
                        // 两两匹配选手
                        List<CompetitionMatchBiSaiVo> teamMatchList = new ArrayList<>();
                        for (int i = 0; i < v.size(); i += 2) {
                            CompetitionApply competitionApply1 = v.get(i);
                            CompetitionApply competitionApply2 = v.get(i + 1);
                            CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
                            match.setCompetitionId(competition1.getId());
                            match.setOrderNum((int) Math.ceil(i / 2) + 1);
                            match.setSchedule(competition1.getSchedule());
                            match.setPlayType(competitionApply1.getApplyType());
                            match.setStatus(0);
                            teamMatchList.add(match);
                            CompetitionMatchTeam matchTeam1 = new CompetitionMatchTeam();
                            matchTeam1.setTeamNo(competitionApply1.getTeamNo());
                            matchTeam1.setTeamType(1);
                            List<CompetitionMatchTeam> list = new ArrayList<>();
                            list.add(matchTeam1);
                            CompetitionMatchTeam matchTeam2 = new CompetitionMatchTeam();
                            matchTeam2.setTeamNo(competitionApply2.getTeamNo());
                            matchTeam2.setTeamType(2);
                            list.add(matchTeam2);
                            match.setList(list);
                        }
                        scheduleMatches(teamMatchList,competitionSites,timeIntervalList,competition1.getPlayTime());
                        matches.addAll(teamMatchList);
                    } else {
                        if(rule.getRegistrationLess()==1){
                            v.forEach(f->{
                                CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
                                match.setCompetitionId(competition1.getId());
                                int scheduleNum = Integer.valueOf(competition1.getSchedule()) + 1;
                                match.setSchedule(scheduleNum+"");
                                match.setPlayType(f.getApplyType());
                                match.setResult(f.getTeamNo());
                                match.setPlayOneScore(0);
                                match.setPlayTwoScore(0);
                                match.setStatus(1);
                                matches.add(match);
                            });
                        }
                    }
                    if (CollectionUtils.isNotEmpty(matches)) {
                        for (CompetitionMatchBiSaiVo bisai : matches) {
                            CompetitionMatch match = new CompetitionMatch();
                            BeanUtils.copyProperties(bisai, match);
                            match.setId(null);
                            int insert = competitionMatchMapper.insert(match);
                            if (insert > 0) {
                                if (CollectionUtils.isNotEmpty(bisai.getList())) {
                                    for (CompetitionMatchTeam matchTeam : bisai.getList()) {
                                        CompetitionMatchTeam matchTeamNo = new CompetitionMatchTeam();
                                        BeanUtils.copyProperties(matchTeam, matchTeamNo);
                                        matchTeamNo.setMatchId(match.getId());
                                        competitionMatchTeamMapper.insert(matchTeamNo);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
    }

    public void paiJifenMatch(Competition competition1,List<CompetitionApply> competitionApplies,List<String> timeIntervalList,CompetitionRule rule,Integer personNum){
        if (CollectionUtils.isNotEmpty(competitionApplies)) {
            Map<Integer, List<CompetitionApply>> collect = competitionApplies.stream().collect(Collectors.groupingBy(CompetitionApply::getApplyType));
            if (ObjectUtils.isNotEmpty(collect)) {
                collect.forEach((k, v) -> {
                    List<CompetitionSite> competitionSites = competitionSiteMapper.selectList(new LambdaUpdateWrapper<CompetitionSite>()
                            .eq(CompetitionSite::getCompetitionId, competition1.getId())
                            .eq(CompetitionSite::getPlayType, k)
                            .eq(CompetitionSite::getSchedule, competition1.getSchedule()));
                    if(CollUtil.isEmpty(competitionSites)){
                        throw new BaseException(0,"赛事场地没有填写！",1);
                    }
                    List<CompetitionMatchBiSaiVo> matches = new ArrayList<>();
                    // 分组后，每组队员大于8个则进行匹配
                    Collections.shuffle(v);
                    int num = 1;
                    if (v.size() > personNum) {
                        List<CompetitionMatchBiSaiVo> teamMatchList = new ArrayList<>();
                        for (int i = 0; i < v.size(); i++) {
                            for (int j = i+1; j < v.size(); j++) {
                                CompetitionApply competitionApply1 = v.get(i);
                                CompetitionApply competitionApply2 = v.get(j);

                                CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
                                match.setCompetitionId(competition1.getId());
                                match.setSchedule(competition1.getSchedule());
                                match.setPlayType(competitionApply1.getApplyType());
                                match.setOrderNum(num);
                                match.setStatus(0);
                                CompetitionMatchTeam matchTeam1 = new CompetitionMatchTeam();
                                matchTeam1.setTeamNo(competitionApply1.getTeamNo());
                                matchTeam1.setTeamType(1);
                                List<CompetitionMatchTeam> list = new ArrayList<>();
                                list.add(matchTeam1);
                                CompetitionMatchTeam matchTeam2 = new CompetitionMatchTeam();
                                matchTeam2.setTeamNo(competitionApply2.getTeamNo());
                                matchTeam2.setTeamType(2);
                                list.add(matchTeam2);
                                match.setList(list);
                                matches.add(match);
                                teamMatchList.add(match);
                                num = num + 1;
                            }
                        }
                        scheduleMatches(teamMatchList,competitionSites,timeIntervalList,competition1.getPlayTime());
                    } else {
                        if(rule.getRegistrationLess()==1){
                            v.forEach(f->{
                                CompetitionMatchBiSaiVo match = new CompetitionMatchBiSaiVo();
                                match.setCompetitionId(competition1.getId());
                                int scheduleNum = Integer.valueOf(competition1.getSchedule()) + 1;
                                match.setSchedule(scheduleNum+"");
                                match.setPlayType(f.getApplyType());
                                match.setResult(f.getTeamNo());
                                match.setPlayOneScore(0);
                                match.setPlayTwoScore(0);
                                match.setStatus(1);
                                matches.add(match);
                            });
                        }
                    }
                    if (CollectionUtils.isNotEmpty(matches)) {
                        for (CompetitionMatchBiSaiVo bisai : matches) {
                            CompetitionMatch match = new CompetitionMatch();
                            BeanUtils.copyProperties(bisai, match);
                            match.setId(null);
                            int insert = competitionMatchMapper.insert(match);
                            if (insert > 0) {
                                if (CollectionUtils.isNotEmpty(bisai.getList())) {
                                    for (CompetitionMatchTeam matchTeam : bisai.getList()) {
                                        CompetitionMatchTeam matchTeamNo = new CompetitionMatchTeam();
                                        BeanUtils.copyProperties(matchTeam, matchTeamNo);
                                        matchTeamNo.setMatchId(match.getId());
                                        competitionMatchTeamMapper.insert(matchTeamNo);
                                    }
                                }
                            }
                        }
                    }
                });

            }
        }
    }

    public List<String> generateTimeSlots(String gameTime,Integer intervalTime) {
        List<String> list = Arrays.asList(gameTime.split(";"));
        List<String> timeSlots = new ArrayList<>();
        list.forEach(f->{
            List<String> list1 = Arrays.asList(f.split("~"));
            String startTime = list1.get(0);
            String endTime = list1.get(1);
            List<String> startList = Arrays.asList(startTime.split(":"));
            List<String> endList = Arrays.asList(endTime.split(":"));
            LocalTime start = LocalTime.of(Integer.parseInt(startList.get(0)), Integer.parseInt(startList.get(1)));  // 起始时间
            LocalTime end = LocalTime.of(Integer.parseInt(endList.get(0)), Integer.parseInt(endList.get(1)));
            LocalTime current = start;
            // 生成时间段
            while (!current.isAfter(end.minusMinutes(intervalTime))) {
                LocalTime next = current.plusMinutes(intervalTime);
                String slot = String.format("%02d:%02d ~ %02d:%02d",
                        current.getHour(), current.getMinute(),
                        next.getHour(), next.getMinute());
                timeSlots.add(slot);
                current = next;
            }
        });
        return timeSlots;
    }

    public void scheduleMatches(List<CompetitionMatchBiSaiVo> matchPairs,List<CompetitionSite> competitionSites, List<String> timeIntervalList,String playTime) {
        // 计算需要的场地数量
        int venuesRequired = (int) Math.ceil(matchPairs.size() / timeIntervalList.size());
        int day = 1;
        int timeSlot = 1;
        int venue = 1;
        String playTimeStr = playTime;
        if(competitionSites.get(0).getOrderNum()!=null){
            timeSlot = competitionSites.get(0).getOrderNum();
        }
        if(competitionSites.get(0).getPlayTime()!=null){
            playTimeStr = competitionSites.get(0).getPlayTime();
        }
        Date playDate = DateUtil.parse(playTimeStr, DatePattern.NORM_DATE_PATTERN);
        for (int i = 0; i <matchPairs.size() ; i++) {
            if (timeSlot > timeIntervalList.size()) {
                timeSlot = 1;
                venue++;
                if (venue > competitionSites.size()) {
                    venue = 1;
                    playTimeStr = DateUtil.offsetDay(playDate, day).toString(DatePattern.NORM_DATE_PATTERN);
                    day++;
                }
            }
            matchPairs.get(i).setOrderNum(timeSlot);
            String startTime = playTimeStr + " " + timeIntervalList.get(timeSlot - 1);
            matchPairs.get(i).setStartTime(startTime);
            matchPairs.get(i).setSiteId(competitionSites.get(venue - 1).getId());
            competitionSites.get(venue-1).setOrderNum(timeSlot);
            competitionSites.get(venue-1).setPlayTime(startTime);
            timeSlot++;
        }
        competitionSites.stream().forEach(f->{
            competitionSiteMapper.updateById(f);
        });

    }

    public Integer generatePairings(int totalTeams,int personNum) {
        // 找出与 personNum 最接近且大于 totalTeams 的 2 的幂次方
        while (personNum < totalTeams) {
            personNum *= 2;
        }
        // 计算轮空的队伍数量
        int byes = personNum - totalTeams;
        return byes;
    }

    public List<Integer> drawByeTeams(int totalTeams,int byeCount){
        // 生成所有队伍编号列表
        List<Integer> allTeams = new ArrayList<>();
        for (int i = 0; i < totalTeams; i++) {
            allTeams.add(i);
        }
        // 打乱队伍顺序
        Collections.shuffle(allTeams, new Random());
        // 抽取轮空队伍
        List<Integer> byeTeams = new ArrayList<>();
        for (int i = 0; i < byeCount; i++) {
            byeTeams.add(allTeams.get(i));
        }
        // 对轮空队伍编号进行排序
        Collections.sort(byeTeams);
        return byeTeams;
    }

    public List<CompetitionApply> getTeamList(List<Integer> byeCount,List<CompetitionApply> allTeams){
        // 取出轮空队伍
        List<CompetitionApply> byeTeams = new ArrayList<>();
        for (int i = 0; i < byeCount.size(); i++) {
            byeTeams.add(allTeams.get(byeCount.get(i)));
        }
        return byeTeams;
    }

    @Override
    public CompetitionMatchDetail playDetail(Integer matchId) {
        return competitionMatchDetailMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchDetail>().eq(CompetitionMatchDetail::getMatchId,matchId));
    }

    @Override
    public void playAdd(CompetitionMatchDetail updateValidate) {
        CompetitionMatchDetail competitionMatchDetail = competitionMatchDetailMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchDetail>().eq(CompetitionMatchDetail::getMatchId, updateValidate.getMatchId()));
        if(ObjectUtils.isEmpty(competitionMatchDetail)){
            competitionMatchDetailMapper.insert(updateValidate);
        }
    }

    @Override
    public void playEdit(CompetitionMatchDetail updateValidate) {
        CompetitionMatchDetail competitionMatchDetail = competitionMatchDetailMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchDetail>().eq(CompetitionMatchDetail::getMatchId, updateValidate.getMatchId()));
        if(ObjectUtils.isNotEmpty(competitionMatchDetail)){
            competitionMatchDetailMapper.updateById(updateValidate);
        }else{
            competitionMatchDetailMapper.insert(updateValidate);
        }
    }

    @Override
    public CompetitionPlayVo play(Integer id,Integer matchId) {
        CompetitionPlayVo play = new CompetitionPlayVo();
        List<Map> maps = competitionMapper.selectCompetitionUserInfo(id, matchId);
        if(CollectionUtils.isNotEmpty(maps)){
            maps.stream().forEach(f->{
                Integer teamTeype = (Integer) f.get("teamType");
                if(teamTeype==1){
                    play.setPlayerOneLogo((String) f.get("logo"));
                    play.setPlayerOne((String) f.get("teamName"));
                    play.setPlayerOneTotalScore(f.get("totalScore").toString());
                }else if(teamTeype==2){
                    play.setPlayerTwoLogo((String) f.get("logo"));
                    play.setPlayerTwo((String) f.get("teamName"));
                    play.setPlayerTwoTotalScore((f.get("totalScore").toString()));
                }
            });
        }
        List<Map> maps1 = competitionMapper.selectCompetitionRound(id, matchId);
        if(CollectionUtils.isNotEmpty(maps1)){
            maps1.stream().forEach(f->{
                Integer scoreNo = (Integer) f.get("scoreNo");
                if(scoreNo==1){
                    play.setPlayerOneOneScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoOneScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==2){
                    play.setPlayerOneTwoScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoTwoScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==3){
                    play.setPlayerOneThreeScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoThreeScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==4){
                    play.setPlayerOneFourScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoFourScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==5){
                    play.setPlayerOneFiveScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoFiveScore(f.get("playTwoTotal").toString());
                }
            });
        }
        List<CompetitionScore> competitionScores = competitionScoreMapper.selectList(new LambdaQueryWrapper<CompetitionScore>().eq(CompetitionScore::getMatchId, matchId));
        if(CollectionUtils.isNotEmpty(competitionScores)){
            play.setRoundList(competitionScores);
        }else{
            play.setRoundList(new ArrayList<>());
        }
        CompetitionMatch competitionMatch = competitionMatchMapper.selectById(matchId);
        CompetitionRule rule = competitionRuleMapper.selectOne(new LambdaUpdateWrapper<CompetitionRule>().eq(CompetitionRule::getCompetitionId, competitionMatch.getCompetitionId()).eq(CompetitionRule::getSchedule, competitionMatch.getSchedule()));
        play.setStatus(competitionMatch.getStatus());
        CompetitionSite competitionSite = competitionSiteMapper.selectOne(new LambdaQueryWrapper<CompetitionSite>()
                .eq(CompetitionSite::getCompetitionId, id)
                .eq(CompetitionSite::getId,competitionMatch.getSiteId())
                .eq(CompetitionSite::getPlayType, competitionMatch.getPlayType()));
        play.setPlayAddress(competitionSite.getAddress());
        play.setPlayAddressName(competitionSite.getName());
        play.setPlayScore(rule.getScoreType());
        return play;
    }

    @Override
    public void playScoreEdit(CompetitionScore updateValidate) throws NoSuchFieldException, IllegalAccessException {
        Integer oneCount = 0;
        Integer twoCount = 0;
        for (int i = 0; i < 60; i++) {
            String fieldName = "round"+(i+1);
            Field field = CompetitionScore.class.getDeclaredField(fieldName);
            // 设置可访问私有字段
            field.setAccessible(true);
            // 获取字段的值
            if(ObjectUtils.isNotEmpty(field.get(updateValidate))) {
                Integer value = (Integer) field.get(updateValidate);
                if (value == 1) {
                    oneCount = oneCount + 1;
                } else if (value == 2) {
                    twoCount = twoCount + 1;
                }
            }
        }
        CompetitionMatch match = competitionMatchMapper.selectById(updateValidate.getMatchId());
        CompetitionRule rule = competitionRuleMapper.selectOne(new LambdaUpdateWrapper<CompetitionRule>().eq(CompetitionRule::getCompetitionId, match.getCompetitionId()).eq(CompetitionRule::getSchedule, match.getSchedule()));
        int i = judgeSingleSet(oneCount, twoCount, rule.getScoreType());
        CompetitionMatchTeam competitionMatchTeam = competitionMatchTeamMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, updateValidate.getMatchId()).eq(CompetitionMatchTeam::getTeamType, i));
        if(ObjectUtils.isNotEmpty(competitionMatchTeam)){
            updateValidate.setWinTeamNo(competitionMatchTeam.getTeamNo());
        }
        updateValidate.setPlayOneTotal(oneCount);
        updateValidate.setPlayTwoTotal(twoCount);
        if(ObjectUtils.isNotEmpty(updateValidate.getScoreId())){
            competitionScoreMapper.updateById(updateValidate);
        }else{
            competitionScoreMapper.insert(updateValidate);
        }
        List<CompetitionScore> competitionScores = competitionScoreMapper.selectList(new LambdaUpdateWrapper<CompetitionScore>().eq(CompetitionScore::getMatchId, updateValidate.getMatchId()));
        JSONObject json = judgeMatch(competitionScores,Integer.parseInt(rule.getRoundCount()),Integer.parseInt(rule.getVictoryCount()),rule.getScoreType());
        if(json!=null){
            Integer winTeam = json.getInteger("winTeam");
            if(winTeam>0) {
                CompetitionMatchTeam team = competitionMatchTeamMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, updateValidate.getMatchId()).eq(CompetitionMatchTeam::getTeamType, winTeam));
                Integer wonByA = json.getInteger("wonByA");
                Integer wonByB = json.getInteger("wonByB");
                CompetitionMatch competitionMatch = new CompetitionMatch();
                competitionMatch.setPlayOneScore(wonByA);
                competitionMatch.setPlayTwoScore(wonByB);
                competitionMatch.setResult(team.getTeamNo());
                competitionMatch.setStatus(2);
                competitionMatch.setId(updateValidate.getMatchId());
                competitionMatchMapper.updateById(competitionMatch);
                CompetitionMatchTeam teamUpdate = new CompetitionMatchTeam();
                teamUpdate.setStatus(1);
                competitionMatchTeamMapper.update(teamUpdate, new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, team.getMatchId()).eq(CompetitionMatchTeam::getTeamNo, team.getTeamNo()));
            }
            Integer lostTeam = json.getInteger("lostTeam");
            if(lostTeam>0){
                CompetitionMatchTeam team = competitionMatchTeamMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, updateValidate.getMatchId()).eq(CompetitionMatchTeam::getTeamType, lostTeam));
                CompetitionMatchTeam teamUpdate = new CompetitionMatchTeam();
                teamUpdate.setStatus(2);
                competitionMatchTeamMapper.update(teamUpdate, new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, team.getMatchId()).eq(CompetitionMatchTeam::getTeamNo, team.getTeamNo()));

            }
        }
    }


    // 判断一局比赛的胜负
    private static int judgeSingleSet(int scoreA, int scoreB, int winScore) {
        // 校验比分数据是否合法
        if (scoreA < 0 || scoreB < 0) {
            throw new IllegalArgumentException("比分不能为负数");
        }

        // 校验是否有一方达到胜利条件
        if (scoreA < winScore && scoreB < winScore) {
            throw new IllegalArgumentException("双方均未达到胜利分数");
        }

        // 校验是否存在分差不足2分的无效高分情况
        if (Math.abs(scoreA - scoreB) < 2) {
            if (scoreA > winScore || scoreB > winScore) {
                throw new IllegalArgumentException("分差不足2分时不能出现超过胜利分数的情况");
            }
        }
        if (scoreA >= winScore && scoreA - scoreB >= 2) {
            return 1;
        } else if (scoreB >= winScore && scoreB - scoreA >= 2) {
            return 2;
        } else if (scoreA >= winScore - 1 && scoreB >= winScore - 1) {
            if (scoreA > scoreB) {
                return 1;
            } else if (scoreB > scoreA) {
                return 2;
            }
        }
        return 0;
    }

    // 判断整场比赛的胜负
    public static JSONObject judgeMatch(List<CompetitionScore> competitionScores,Integer roundCount,Integer victoryCount,Integer playScore) {
        JSONObject jsonObject = new JSONObject();
        if(CollectionUtils.isNotEmpty(competitionScores)) {
            int setsWonByA = 0;
            int setsWonByB = 0;
            int winTeam = 0;
            int lostTeam = 0;
            for (CompetitionScore setScore : competitionScores) {
                int winner = judgeSingleSet(setScore.getPlayOneTotal(), setScore.getPlayTwoTotal(), playScore);
                if (winner == 1) {
                    setsWonByA++;
                } else if (winner == 2) {
                    setsWonByB++;
                }
            }
            if (setsWonByA >= roundCount / victoryCount + 1) {
                winTeam = 1;
                lostTeam = 2;
            } else if (setsWonByB >= roundCount / victoryCount + 1) {
                lostTeam = 1;
                winTeam = 2;
            }
            jsonObject.put("wonByA",setsWonByA);
            jsonObject.put("wonByB",setsWonByB);
            jsonObject.put("winTeam",winTeam);
            jsonObject.put("lostTeam",lostTeam);

        }
        return jsonObject;
    }

    @Override
    public PageResult<Map> scheduleList(PageValidate pageValidate, CompetitionScheduleSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();
        Map<String, Object> param = BeanMapUtils.create(searchValidate);
        IPage<Map> iPage = competitionMapper.selectscheduleList(new Page<>(page, limit),param);
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    @Override
    public PageResult<Map> scoreList(PageValidate pageValidate, CompetitionScoreSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();
        Map<String, Object> param = BeanMapUtils.create(searchValidate);
        IPage<Map> iPage = competitionMapper.selectScorelist(new Page<>(page, limit),param);
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    @Override
    public void sessionUp(CompetitionSessionDownValidate sessionValidate) {
        CompetitionMatch match = new CompetitionMatch();
        match.setId(sessionValidate.getId());
        match.setOrderNum(sessionValidate.getDownOrderNum());
        match.setStartTime(sessionValidate.getDownStartTime());
        competitionMatchMapper.updateById(match);
        match.setId(sessionValidate.getDownId());
        match.setOrderNum(sessionValidate.getOrderNum());
        match.setStartTime(sessionValidate.getStartTime());
        competitionMatchMapper.updateById(match);
    }

    @Override
    public void sessionDown(CompetitionSessionDownValidate sessionValidate) {
        sessionUp(sessionValidate);
    }

    @Override
    public CompetitionMatch scheduleDetail(Integer id) {
//        return competitionMapper.selectSchedule(id);
        return competitionMatchMapper.selectById(id);
    }

    @Override
    public void scheduleEdit(CompetitionScheduleCreateValidate createValidate) {
        CompetitionMatch match = new CompetitionMatch();
        BeanUtils.copyProperties(createValidate,match);
        competitionMatchMapper.updateById(match);
    }
}
